import 'dart:io';

import 'package:aio/aio.dart';
import 'package:flutter/cupertino.dart';
import 'package:app/src/config/app_data_config.dart';
import 'package:app/src/ui/app_ui.dart';
import 'package:app/src/http/bean/http_data.dart';
import 'package:app/src/http/bean/user.dart';
import 'package:app/src/http/sign.dart';
import 'package:app/src/http/url.dart';
import 'package:app/src/manager/user_manager.dart';
import 'package:app/src/ui/dialog/dailog.dart';

import '../../../generated/app_strings.dart';
import '../bean/worksdo/material_requisition_bean.dart';
import '../bean/wroks/dispatchingaudit_bean.dart';

///用户登录，获取用户信息
class UserModel {
  ///登录
  static void login(
      BuildContext context,
      bool isEnableLoad,
      UserPassData? userPassData,
      ResponseCallbackWithT<AppHttpResult<UserInfo, String>> callback) {
    var url = Url.baseurl() + Url.userlogin;
    var queryParameters = Map<String, dynamic>();
    var data = userPassData?.jsonEncodeToJson();
    var token = AppDataConfig.getToken();
    queryParameters['data'] = data;
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // print('成功:\n$result');
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..contentType = ContentType.form
      ..isAllowedRepeat = true
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<UserInfo, String>>(AppHttpResult()
            ..Data = UserInfo()
            ..t2 = '')
          ?.then((result) {
        //print(result.toString());
        callback?.call(result);
      });
  }

  ///密码修改
  static void changepassword(
      BuildContext context,
      bool isEnableLoad,
      UserPassData? userPassData,
      ResponseCallbackWithT<AppHttpResult<String, String>> callback) {
    var url = Url.baseurl() + Url.changepassword;
    var queryParameters = Map<String, dynamic>();
    var data = userPassData?.jsonEncodeToJson();
    var token = AppDataConfig.getToken();
    queryParameters['data'] = data;
    var sign = getSign(queryParameters);
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        AppDialog.showDialogWithError(context, code, error);
      })
      // ..onSuccess((result) {
      //   print('成功:\n$result');
      // })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormData('data', data)
      ..addFormData('sign', sign)
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<String, String>>(AppHttpResult()
            ..Data = ""
            ..t2 = '')
          ?.then((result) {
        //print(result.toString());
        callback?.call(result);
      });
  }

  ///修改用户信息;信息修改成功后，不会返回用户信息。需要自己重新获取。
  static void setpersoninfo(
      BuildContext context,
      bool isEnableLoad,
      UserInfo? userInfo,
      ResponseCallbackWithT<AppHttpResult<String, String>> callback) {
    var url = Url.baseurl() + Url.setpersoninfo;
    var queryParameters = Map<String, dynamic>();
    var data = userInfo?.jsonEncodeToJSONObject();
    //print('data:\t${data}');
    queryParameters['data'] = data;
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    var token = AppDataConfig.getToken();
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        AppDialog.showDialogWithError(context, code, error);
      })
      // ..onSuccess((result) {
      //   print('成功:\n$result');
      // })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<String, String>>(AppHttpResult()
            ..Data = ""
            ..t2 = '')
          ?.then((result) {
        //print(result.toString());
        callback?.call(result);
      });
  }

  ///获取用户信息
  static void getpersoninfo(BuildContext context, bool isEnableLoad,
      ResponseCallbackWithT<AppHttpResult<UserInfo?, String?>> callback) {
    UserPassData? userPassData = UserManager.getUserPassData();
    if (userPassData == null || StringUtils.isEmpty(userPassData?.UserName)) {
      return;
    }
    var url = Url.baseurl() + Url.getpersoninfo;
    var queryParameters = Map<String, dynamic>();
    var data = userPassData?.jsonEncodeToJson();
    var token = AppDataConfig.getToken();
    queryParameters['data'] = data;
    var sign = getSign(queryParameters);
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // print('用户信息获取成功:\n$result');
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormData('data', data)
      ..addFormData('sign', sign)
      // ..isAllowedRepeat = false //是否允许重复请求
      ..isAllowedRepeat = true
      ..isUpdateCallback = true //实时更新回调函数
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<UserInfo?, String?>>(AppHttpResult()
            ..Data = UserInfo()
            ..t2 = '')
          ?.then((result) {
        //print("请求结果：=======================================");
        callback?.call(result);
      });
  }

  ///扫码授权登录
  ///code 识别码
  ///authorization 0 查询是否过期，1授权登录
  static void setscancode(
      BuildContext context,
      bool isEnableLoad,
      String code,
      String authorization,
      ResponseCallbackWithT<AppHttpResult<UserInfo?, String?>> callback) {
    var url = Url.baseurl() + Url.setscancode;
    var queryParameters = Map<String, dynamic>();
    var token = AppDataConfig.getToken();
    queryParameters['data'] = code;
    queryParameters['authorization'] = authorization;
    queryParameters['factoryId'] = AppDataConfig.getFactory()?.FactoryId;
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        AppDialog.showDialogWithError(context, code, error);
      })
      // ..onSuccess((result) {
      //   print('成功:\n$result');
      // })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..isAllowedRepeat = false //是否允许重复请求
      ..isUpdateCallback = true //实时更新回调函数
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<UserInfo?, String?>>(AppHttpResult()
            ..Data = UserInfo()
            ..t2 = '')
          ?.then((result) {
        //print("请求结果：=======================================");
        callback?.call(result);
      });
  }

  ///文件上传
  ///files 文件
  static void syspicupload(
      BuildContext context,
      bool isEnableLoad,
      List<File> files,
      ResponseCallbackWithT<AppHttpResult<String?, String?>> callback) {
    // print("图片开始上传$files");
    // fixme 第一次上传
    _syspicupload(context, isEnableLoad, files, (value) {
      //{"Data":"~/photo/202212/10842/1671505532539_0.jpg","MsgCode":"100","MsgDetail":"上传成功"}
      //{"Data":null,"MsgCode":"103","MsgDetail":"图片张数错误"}
      if (value.MsgCode == "103" ||
          (value.MsgCode == "100" && StringUtils.isEmpty(value.Data))) {
        print("图片上传失败，重新上传2：${value.toString()}");
        if (files != null && files.length > 0) {
          ///fixme 第二次上次；重新上传一次。防止因为网络问题。而导致上传失败的问题。
          _syspicupload(context, isEnableLoad, files, (value) {
            // callback?.call(value);
            //fixme 连续上传3次。保险一点。
            if (value.MsgCode == "103" ||
                (value.MsgCode == "100" && StringUtils.isEmpty(value.Data))) {
              print("图片上传失败，重新上传3：${value.toString()}");
              if (files != null && files.length > 0) {
                ///fixme 第三次上传：重新上传一次。防止因为网络问题。而导致上传失败的问题。
                _syspicupload(context, isEnableLoad, files, (value) {
                  callback?.call(value);
                }, uploadCount: 3);
              } else {
                callback?.call(value);
              }
            } else {
              callback?.call(value);
            }
          }, uploadCount: 2);
        } else {
          callback?.call(value);
        }
      } else {
        callback?.call(value);
      }
    }, uploadCount: 1);
  }

  ///文件上传
  ///files 文件
  ///uploadCount 文件上传次数
  static void _syspicupload(
      BuildContext context,
      bool isEnableLoad,
      List<File> files,
      ResponseCallbackWithT<AppHttpResult<String?, String?>> callback,
      {int uploadCount = 1}) {
    var url = Url.baseurl() + Url.syspicupload;
    var queryParameters = Map<String, dynamic>();
    var token = AppDataConfig.getToken();
    queryParameters['num'] = files.length;
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    // print('签名：$sign');
    // files.forEach((element) {
    //   print("上传文件：\t${element?.path}");
    //   element.length()?.then((value) {
    //     var size = FileUtils.getSizeForMB(value);
    //     print("上传文件大小：$size MB");
    //   });
    // });
    // var starData = DateTime.now();
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      ..onStart(() {
        // print('开始上传：${Url.syspicupload}');
      })
      ..onError((code, error) {
        print('上传错误:\t$code\t$error');
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        //{"Data":"~/photo/202212/10842/1671505532539_0.jpg","MsgCode":"100","MsgDetail":"上传成功"}
        //{"Data":null,"MsgCode":"103","MsgDetail":"图片张数错误"}
        //{"Data":null,"MsgCode":"103","MsgDetail":"图片格式错误"}
        // var starData2 = DateTime.now();
        // var d = starData2.difference(starData);
        // print('上传成功返回:\n$result\t 耗时：${d.inSeconds}秒');
        // print('上传成功返回:\n$result');
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFiles(files)
      ..addFormDatas(queryParameters)
      ..isAllowedRepeat = false //是否允许重复请求
      ..isUpdateCallback = true //实时更新回调函数
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<String?, String?>>(AppHttpResult()
            ..Data = ''
            ..t2 = '')
          ?.then((result) {
        // print("图片上传结果：=======================================$result");
        if (result.isSuccessForCode()) {
          //print("请求结果：=======================================");
          //fixme 建波浪号~全部替换成服务器域名地址。图片地址多几个//是没有关系的，是可以正常访问的。亲测可行。
          //fixme 多个图片地址是用|分开的。
          result?.Data = result?.Data?.replaceAll("~", Url.baseurl());
          if (StringUtils.isEmpty(result?.Data) && context != null) {
            //fixme 图片上传失败，请重新再试
            // AppDialog.showDialogWithInfo(context,
            //     content: AppStrings.of(context).Takephotostoplay3);
            if (uploadCount >= 3) {
              //fixme 不回调，直接提示(不回调结果)：图片上传失败，请重新再试
              AppDialog.showDialogWithInfo(context,
                  content: AppStrings.of(context).Takephotostoplay3);
            } else {
              //fixme 回调
              callback?.call(result);
            }
          } else {
            callback?.call(result); //fixme 上传成功，直接回调。
          }
        } else {
          if (uploadCount >= 3) {
            //fixme 不回调，直接提示(不回调结果)：图片上传失败，请重新再试
            AppDialog.showDialogWithInfo(context,
                content: AppStrings.of(context).Takephotostoplay3);
          } else {
            //fixme 回调
            callback?.call(result);
          }
        }
      });
  }

  ///获取销售经理（业务员）
  static void getManagergetlistWith02(
      BuildContext context,
      bool isEnableLoad,
      ResponseCallbackWithT<AppHttpResult<List<UserInfo>?, UserInfo?>>
          callback) {
    return getManagergetlist(context, "02", isEnableLoad, callback);
  }

  ///获取销售经理或客服经理条目
  /// worktype worktype 工种 : “02”销售经理(业务员); “03”客服经理
  static void getManagergetlist(
      BuildContext context,
      String worktype,
      bool isEnableLoad,
      ResponseCallbackWithT<AppHttpResult<List<UserInfo>?, UserInfo?>>
          callback) {
    var url = Url.baseurl() + Url.Managergetlist;
    var queryParameters = Map<String, dynamic>();
    var subData = SubData();
    subData.commondata = CommonData();
    subData.worktype = worktype;
    queryParameters['data'] = subData.jsonEncodeToJson();
    var token = AppDataConfig.getToken();
    var sign = getSign(queryParameters);
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      ..onStart(() {
        //print('开始:\t${queryParameters['data']}');
      })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // print('成功:\n$result');
      })
      ..onFinish(() {
        // print('结束');
      })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..addFormData('sign', sign)
      ..isAllowedRepeat = true //是否允许重复请求
      ..isUpdateCallback = true //实时更新回调函数
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..isCache(true)
      ..postASync<AppHttpResult<List<UserInfo>?, UserInfo?>>(AppHttpResult()
            ..Data = <UserInfo>[]
            ..t2 = UserInfo())
          ?.then((result) {
        //print("请求结果：=======================================");
        callback?.call(result);
      });
  }

  ///获取销售经理或客服经理条目
  ///{"type":"Process"}//工序
  // {"type":"Group","processId":""}//班组
  static void getOtherWorkApply(
      BuildContext context,
      ProcessQuery processQuery,
      bool isEnableLoad,
      ResponseCallbackWithT<
              AppHttpResult<List<OtherWorkApply>?, OtherWorkApply?>>
          callback) {
    var url = Url.baseurl() + Url.getOtherWorkApply;
    var queryParameters = Map<String, dynamic>();
    // var subData = SubData();
    // subData.commondata = CommonData();
    // queryParameters['data'] = subData.jsonEncodeToJson();
    queryParameters['data'] = processQuery.jsonEncodeToJson();
    var token = AppDataConfig.getToken();
    var sign = getSign(queryParameters);
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      ..onStart(() {
        //print('开始:\t${queryParameters['data']}');
      })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // print('成功:\n$result');
      })
      ..onFinish(() {
        // print('结束');
      })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..addFormData('sign', sign)
      ..isAllowedRepeat = true //是否允许重复请求
      ..isUpdateCallback = true //实时更新回调函数
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..isCache(true)
      ..postASync<AppHttpResult<List<OtherWorkApply>?, OtherWorkApply?>>(
              AppHttpResult()
                ..Data = <OtherWorkApply>[]
                ..t2 = OtherWorkApply())
          ?.then((result) {
        //print("请求结果：=======================================");
        callback?.call(result);
      });
  }

  ///获取部门
  static void getDepartments(
      BuildContext context,
      bool isEnableLoad,
      ResponseCallbackWithT<AppHttpResult<List<Department>?, Department?>>
          callback) {
    var url = Url.baseurl() + Url.SelectPersonnel;
    var queryParameters = Map<String, dynamic>();
    // var subData = SubData();
    // subData.commondata = CommonData();
    // queryParameters['data'] = subData.jsonEncodeToJson();
    queryParameters['data'] = '''
      {"type":"dept","DeptId":"","PersonName":"","PersonCode":""}
     ''';
    var token = AppDataConfig.getToken();
    var sign = getSign(queryParameters);
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      ..onStart(() {
        //print('开始:\t${queryParameters['data']}');
      })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        //print('成功:\n$result');
      })
      ..onFinish(() {
        // print('结束');
      })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..addFormData('sign', sign)
      ..isAllowedRepeat = true //是否允许重复请求
      ..isUpdateCallback = true //实时更新回调函数
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..isCache(true)
      ..postASync<AppHttpResult<List<Department>?, Department?>>(AppHttpResult()
            ..Data = <Department>[]
            ..t2 = Department())
          ?.then((result) {
        //print("请求结果：=======================================");
        callback?.call(result);
      });
  }

  ///获取申请人
  static void getApplicant(
      BuildContext context,
      bool isEnableLoad,
      ResponseCallbackWithT<AppHttpResult<List<UserApplicant>?, UserApplicant?>>
          callback) {
    var url = Url.baseurl() + Url.SelectPersonnel;
    var queryParameters = Map<String, dynamic>();
    // var subData = SubData();
    // subData.commondata = CommonData();
    // queryParameters['data'] = subData.jsonEncodeToJson();
    queryParameters['data'] = '''
      {"type":"userdata","DeptId":"","PersonName":"","PersonCode":""}
     ''';
    var token = AppDataConfig.getToken();
    var sign = getSign(queryParameters);
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      ..onStart(() {
        //print('开始:\t${queryParameters['data']}');
      })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        //print('成功:\n$result');
      })
      ..onFinish(() {
        // print('结束');
      })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..addFormData('sign', sign)
      ..isAllowedRepeat = true //是否允许重复请求
      ..isUpdateCallback = true //实时更新回调函数
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..isCache(true)
      ..postASync<AppHttpResult<List<UserApplicant>?, UserApplicant?>>(
              AppHttpResult()
                ..Data = <UserApplicant>[]
                ..t2 = UserApplicant())
          ?.then((result) {
        //print("请求结果：=======================================");
        callback?.call(result);
      });
  }
}
